package com.kaede.hayate.modules.api.controller;

import com.kaede.hayate.common.debug.JavaClassExecuter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "Debug")
@RestController
@RequestMapping("${application.api-prefix}")
public class DebugController {

    @ApiOperation("热运行代码")
    @GetMapping("debug")
    public ResponseEntity debug(String clazzPath){
        Map<String, String> response = new HashMap<>();
        response.put("path", getClass().getClassLoader().getResource("").getPath());
        if(!StringUtils.isEmpty(clazzPath)){
            try (InputStream is = new FileInputStream(clazzPath)){
                byte[] b = new byte[is.available()];
                is.read(b);
                is.close();
                response.put("result", JavaClassExecuter.execute(b));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ResponseEntity.ok(response);
    }
}
